package main;

/**
 * 
 * @author Dylan
 * 
 * A basic sprite object for 2d games - layered so that certain sprites appear on top.
 * Displays a single image.
 * 
 */

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

public class Sprite implements Comparable<Sprite> {
	public int layer;
	public double x, y, rot;
	public double radius;

	private BufferedImage image;
	int w, h;

	public Sprite(BufferedImage image, int layer) {
		this.image = image;
		this.layer = layer;
		x = y = 0;
		radius = getImageRadius(image);
		System.out.println(radius);
	}

	public Sprite(int layer) {
		this.image = null;
		this.layer = layer;
		x = y = 0;
	}
	
	public void setImage(BufferedImage image){
		this.image = image;
		radius = getImageRadius(image);
	}
	
	public double getImageRadius(BufferedImage img){
		
		if (img == null){
			return 0;
		}else{
			w = image.getWidth();
		h = image.getHeight();
			return .5 * Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2));
		}
	}
	
	public BufferedImage rotateImage(BufferedImage img, int angle){
		int w = img.getWidth();
		int h = img.getHeight();
		BufferedImage rotImage = new BufferedImage(w, h, img.getType());
		Graphics2D g = rotImage.createGraphics();
		g.rotate(Math.toRadians(angle), w/2, h/2);
		g.drawImage(img, null, 0, 0);
		return rotImage;
	}
	
	public void draw(Graphics g) {
		if (rot % 360 != 0) {
			g.drawImage(rotateImage(image, (int)rot), (int) x - w / 2, (int) y - h / 2, null);
		} else {
			g.drawImage(image, (int) x - w / 2, (int) y - h / 2, null);
		}
	}

	public int compareTo(Sprite sprite) {
		if (sprite.layer > this.layer) {
			return -1;
		} else if (sprite.layer < this.layer) {
			return 1;
		} else {
			return 0;
		}
	}
	
	public boolean intersects(Sprite sprite){
		return (Math.sqrt(Math.pow(x - sprite.x, 2) + Math.pow(y - sprite.y, 2)) < radius + sprite.radius);
	}

}
